package com.bytedance.video.service.impl;

import com.bytedance.video.common.*;
import com.bytedance.video.mapper.RelationMapper;
import com.bytedance.video.mapper.UserFavMapper;
import com.bytedance.video.mapper.VideoMapper;
import com.bytedance.video.pojo.Relation;
import com.bytedance.video.pojo.User;
import com.bytedance.video.pojo.UserFavorite;
import com.bytedance.video.pojo.Video;
import com.bytedance.video.request.PublishVideoActionRequest;
import com.bytedance.video.request.PublishVideoListRequest;
import com.bytedance.video.request.VideoFeedRequest;
import com.bytedance.video.respones.PublishVideoActionResponses;
import com.bytedance.video.respones.PublishVideoListResponses;
import com.bytedance.video.respones.VideoFeedRespones;
import com.bytedance.video.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class VideoServiceImpl implements VideoService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private UserFavMapper userFavMapper;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private RelationMapper relationMapper;

    /**
     * 不限制登录状态，返回按投稿时间倒序的视频列表，视频数由服务端控制，单次最多30个。
     *
     * @return
     */
    @Override
    public VideoFeedRespones provideVideo(VideoFeedRequest videoFeedRequest) {
        //根据时间返回最新更新的视频
        List<Video> videoList = videoMapper.selectAllVideo();
        //如果已经登录，则从token的载荷解析出userId,如果未登录，则不解析token载荷
        String token = videoFeedRequest.getToken();
        Long currentUserId = null;
        if (token != null) {
            currentUserId = JwtUtil.parseToken(token);
        }
        for (Video video : videoList) {
            Long userId = video.getUser_id();
            User user = videoMapper.selectUserById(userId);
            if (currentUserId != null) {
                //说明当前用户已登录
                //获取videoId
                Long videoId = video.getId();
                //根据currentUserId去查询user_favorite表，是否存在点赞关系，设置setIs_follow属性
                UserFavorite userFavorite = userFavMapper.selectUserIsFavorite(currentUserId, videoId);
                if (userFavorite == null) {
                    //说明当前刷抖声不存在点赞关系
                    video.setIs_favorite(false);
                } else if (userFavorite != null) {
                    //说明当前刷抖声存在点赞关系,不允许再点赞
                    video.setIs_favorite(true);
                }
            }
            /**
             * 查询当前用户和视频作者是否存在关注关系,处理是否关注属性
             * 自己对自己不设置user的Is_follow
             */
            Relation relation = relationMapper.selectIsFollow(currentUserId, userId);
            if (relation == null) {
                //说明未关注
                user.setIs_follow(false);
            } else if (relation != null) {
                user.setIs_follow(true);
            }
            video.setAuthor(user);
        }
        VideoFeedRespones videoFeedRespones = new VideoFeedRespones();
//        本次返回的视频中，发布最早的时间，作为下次请求时的latest_time
//        videoFeedRespones.setNext_time();
        videoFeedRespones.setVideo_list(videoList);
        videoFeedRespones.setStatus_code(StatusCode.STATUS_OK);
        videoFeedRespones.setStatus_msg("视频返回成功！");
        return videoFeedRespones;
    }

    /**
     * 视频投稿
     * 将视频上传，视频封面上传
     * 解析token取出user_id
     * 将user_id，视频的tile，视频url，封面url，uuid作为video_id写入数据库
     * <p>
     * 此时改变user的作品总数
     * <p>
     * 修改user表中的作品数
     *
     * @return
     */
    @Override
    @Transactional
    public PublishVideoActionResponses publishVideo(PublishVideoActionRequest publishVideoActionRequest) throws IOException {

        MultipartFile multipartFile = publishVideoActionRequest.getData();
        String uuid = UUID.randomUUID().toString();
        int lastIndexOf = multipartFile.getOriginalFilename().lastIndexOf(".");
        //后缀名 例如  .mp4
        String lastName = multipartFile.getOriginalFilename().substring(lastIndexOf);
        //文件名，包含后缀
        String fileName = uuid + lastName;
//        byte[] multipartFileBytes = multipartFile.getBytes();
//        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(multipartFileBytes);
        String realPath = httpServletRequest.getServletContext().getRealPath("/") + fileName;
        //转存文件
        multipartFile.transferTo(new File(realPath));
        String token = httpServletRequest.getParameter("token");
        Long userid = JwtUtil.parseToken(token);
        log.info("解析出来的userid:" + userid);
        //查询是否存在该userid
        User user1 = videoMapper.selectUserById(userid);
        PublishVideoActionResponses publishVideoActionResponses = new PublishVideoActionResponses();
        if (user1 == null) {
            publishVideoActionResponses.setStatus_code(StatusCode.STATUS_FAIL);
            publishVideoActionResponses.setStatus_msg("上传失败！你的用户已被删除！");
            return publishVideoActionResponses;
        }
        //这里使用异步处理防止前端请求超时，将视频和截图上传云存储
        HandlerUploadFileThread handlerUploadFileThread = new HandlerUploadFileThread();
        handlerUploadFileThread.setLocalFilePath(realPath);
        handlerUploadFileThread.setUserid(userid);
        handlerUploadFileThread.setFileName(fileName);
        handlerUploadFileThread.setUuid(uuid);
        handlerUploadFileThread.setLastName(lastName);
        handlerUploadFileThread.setPublishVideoActionRequest(publishVideoActionRequest);
        handlerUploadFileThread.setVideoMapper(videoMapper);
        Thread thread = new Thread(handlerUploadFileThread);
        thread.start();
        //修改该用户的作品总数
        User user = videoMapper.selectUserById(userid);
        videoMapper.updateUserWorkCount(userid, user.getWork_count() + 1);
        publishVideoActionResponses.setStatus_code(StatusCode.STATUS_OK);
        publishVideoActionResponses.setStatus_msg("上传成功！");
        return publishVideoActionResponses;
    }

    /**
     * /douyin/publish/list/ - 发布列表
     * 登录用户的视频发布列表，直接列出用户所有投稿过的视频。
     * 接口类型
     * GET
     * <p>
     * 修改作品输数量
     *
     * @param publishVideoListRequest
     * @return
     */
    @Override
    public PublishVideoListResponses getUsersVideoList(PublishVideoListRequest publishVideoListRequest) {
        //取出userid
        Long userId = publishVideoListRequest.getUser_id();
        //查询userid对应的videos
        List<Video> videoList = videoMapper.selectVideoByUserId(userId);
        for (Video video : videoList) {
            Long user_id = video.getUser_id();
            User user = videoMapper.selectUserById(user_id);
            video.setAuthor(user);
        }
        PublishVideoListResponses publishVideoListResponses = new PublishVideoListResponses();
        publishVideoListResponses.setVideo_list(videoList);
        publishVideoListResponses.setStatus_code(StatusCode.STATUS_OK);
        publishVideoListResponses.setStatus_msg("成功获取该用户发布的视频！");
        return publishVideoListResponses;
    }
}
